import { Component, OnInit, Input, Output, EventEmitter, ElementRef, NgZone } from '@angular/core';
import { FSUtils } from '../../utils/fsutils';
import { JSZipWrapper } from '../../utils/ziputils';
import { BaseComponent } from '../base.component';
import { ElectronService } from '../../providers/electron.service';
import { CommonUtils } from '../../utils/commonutils';

@Component({
  selector: 'app-zipview',
  templateUrl: './zipview.component.html',
  styleUrls: ['./zipview.component.scss']
})
export class ZipviewComponent extends BaseComponent implements OnInit {

  error: string;
  entries: any[];
  isLoading = true;
  previewImagePath: string;
  previewVideoPath: string;
  previewText: string;
  @Input() zipFile: string;
  @Output() whenBeforeLoad = new EventEmitter();
  @Output() whenLoadCompleted = new EventEmitter();
  /**在根目录中发起向上层导航操作 */
  @Output() whenNavigateRoot = new EventEmitter();
  private zip: JSZipWrapper;
  private currentDirectory = '/';
  constructor(electronService: ElectronService, el: ElementRef, private zone: NgZone) {
    super(electronService, el);
  }

  ngOnInit() {
    if (!FSUtils.isHttp(this.zipFile)) {
      if (!FSUtils.fileExists(this.zipFile)) {
        this.error = `文件:${this.zipFile}不存在`;
      } else {
        this.dataLoad('');
      }
    }
  }
  /**获取当前目录 */
  get curDirectory() {
    return this.currentDirectory;
  }
  onCloseViewer() {
    this.previewImagePath = null;
    this.previewVideoPath = null;
    this.previewText = null;
  }
  openEntry(zipEntry: any) {
    if (zipEntry) {
      let entry: any;
      if (typeof(zipEntry) === 'string') {
        entry = this.zip.getEntry(zipEntry);
      } else {
        entry = zipEntry;
      }
      if (entry.dir) {
        this.dataLoad(entry.name);
      } else {
        const entryName = entry.name;
        let ext = entryName;
        ext = ext.lastIndexOf('.') > -1 ? ext.substring(ext.lastIndexOf('.')) : ext;
        if (CommonUtils.isImage(ext)) {
          this.onCloseViewer();
          this.setLoadingFlag(true);
          this.zip.readAsBase64Async(entryName, (error, base64) => {
            if (!error) {
              let mimeType = 'image/jpeg';
              if (CommonUtils.isPngImage(ext)) {
                mimeType = 'image/png';
              } else if (CommonUtils.isGifImage(ext)) {
                mimeType = 'image/gif';
              } else if (CommonUtils.isBmpImage(ext)) {
                mimeType = 'image/bmp';
              }
              this.previewImagePath = CommonUtils.makeURI(base64, mimeType);
              console.log(this.previewImagePath);
            } else {
              this.previewText = error;
            }
            this.setLoadingFlag(false);
          });
        } else if (CommonUtils.isMp4(ext)) {
          this.onCloseViewer();
          this.setLoadingFlag(true);
          this.zip.extractEntryTo(entryName, this.electronService.getTempPath()
          , (error, file) => {
            if (!error) {
              const url = require('url');
              this.previewVideoPath = 'file:///' + url.format(file);
            } else {
              this.previewText = error;
            }
            this.setLoadingFlag(false);
          }, true, true);
        } else if (CommonUtils.isTextFormat(ext)) {
          this.onCloseViewer();
          this.setLoadingFlag(true);
          this.zip.readAsTextAsync(entryName, (error, text) => {
            if (!error) {
              this.previewText = text;
            } else {
              this.previewText = error;
            }
            this.setLoadingFlag(false);
          });
        }
      }
    }
  }
  /**
   * 返回上层目录
   */
  gotoLastLevel() {
    if (this.currentDirectory) {
      if (!this.isInRoot) {
        let temp = this.currentDirectory.endsWith('/') ?
        this.currentDirectory.substring(0, this.currentDirectory.length - 1) : this.currentDirectory;
        if (temp.lastIndexOf('/') > -1) {
          // 回到上级目录
          temp = temp.substring(0, temp.lastIndexOf('/'));
          temp = temp !== '' ? `${temp}/` : temp;
        } else {
          // 回到根目录
          temp = '';
        }
        this.dataLoad(temp);
        return;
      }
    }
    if (this.whenNavigateRoot) {
      this.whenNavigateRoot.emit(this);
    }
  }
  /**
   * 获取zip条目对应的图片
   * @param entry zip条目
   */
  getEntryImage(entry: any): string {
    let name = '';
    if (!entry.dir) {
      const pointPos = entry.name.lastIndexOf('.');
      name = entry.name.substring(pointPos + 1);
    } else {
      name = 'folder';
    }
    return `./assets/files/${name}.png`;
  }
  /**
   * 获取条目显示名称
   * @param entry zip条目
   */
  getEntryDisplayName(entry: any) {
    if (entry.dir) {
      let temp = entry.name;
      if (entry.name.endsWith('/')) {
        temp = entry.name.substring(0, entry.name.length - 1);
      }
      if (temp.lastIndexOf('/') > -1) {
        return temp.substring(temp.lastIndexOf('/') + 1);
      }
      return temp;
    } else {
      if (entry.name.lastIndexOf('/') > -1) {
        return entry.name.substring(entry.name.lastIndexOf('/') + 1);
      }
    }
    return entry.name;
  }
  /**
   * 获取是否在根目录
   */
  get isInRoot() {
    return !this.currentDirectory || this.currentDirectory === ''
    || this.currentDirectory === '/';
  }
  /**
   * 加载当前路径下包含的zip条目
   * @param folder 路径
   */
  private dataLoad (folder: string) {
    this.setLoadingFlag(true);
    this.currentDirectory = !folder || folder === '' ? '/'
    : (folder.endsWith('/') ? folder : `${folder}/`);
    if (this.whenBeforeLoad) {
      this.whenBeforeLoad.emit();
    }
    const _loadEntries = () => {
      const entries = this.zip.getEntries();
      folder = !folder ? '' : folder;
      let directories = [];
      let files = [];
      entries.forEach(entry => {
        let entryName = entry.name;
        if (folder === '' || (folder !== '' && entryName.indexOf(folder) === 0)) {
          if (folder !== '') {
            entryName = entryName.substring(folder.length);
          }
          const array = entryName.split('/');
          if ((!entry.dir && array.length === 1)
          || (entry.dir && array.length === 2)) {
            if (entry.dir) {
              directories.push(entry);
            } else if (!entry.dir) {
              files.push(entry);
            }
          }
        }
      });
      directories = directories.sort((first, second) => {
        return first.name > second.name ? 1 : 0;
      });
      files = files.sort((first, second) => {
        return first.name > second.name ? 1 : 0;
      });
      this.entries = directories.concat(files);
      if (this.whenLoadCompleted) {
        this.whenLoadCompleted.emit(this);
      }
      this.setLoadingFlag(false);
    };
    if (this.zip) {
      _loadEntries();
    } else {
      let zipUri: string;
      zipUri = this.zipFile;
      // zipUri = 'http://istudyway-huabei3.oss-cn-zhangjiakou.aliyuncs.com/file/software/2019-03-07/XZz3PCNZDx.zip';
      this.zip = new JSZipWrapper(zipUri
      , (error, zip) => {
        if (error) {
          this.error = error;
          if (this.whenLoadCompleted) {
            this.whenLoadCompleted.emit(this);
          }
          this.setLoadingFlag(false);
        } else {
          _loadEntries();
        }
      });
    }
  }
  /**
   * 设置载入状态
   * @param isLoading 当前载入状态
   */
  private setLoadingFlag(isLoading: boolean) {
    if (this.zone) {
      this.zone.run(() => {
        this.isLoading = isLoading;
      });
    } else {
      this.isLoading = isLoading;
    }
  }
}
